package com.ericsson.bscs.cmstest.clients ;

import java.util.ArrayList ;
import java.util.Calendar ;
import java.util.List ;
import java.util.logging.Logger ;

/**
 * @author Igor Kostin: igor.kstn@gmail.com
 * 
 */
public class SOILoaderClient
{
	private final static Logger logger = Logger.getLogger(SOILoaderClient.class.getCanonicalName()) ;

	public static void main(final String[] args) throws Exception
	{
		if (args.length == 0)
		{
			printUssage() ;
			return ;
		}

		final Class<?> executorClass = Class.forName(args[0]) ;

		// DB INITIALIZATION
		SOILoaderDBHandler soidb = null ;
		try
		{
			soidb = new SOILoaderDBHandler() ;

			final int threadNumber = Integer.parseInt(args[1]) ;
			final int runPeriodMinutes = Integer.parseInt(args[2]) ;

			Thread th ;
			final List<Thread> threads = new ArrayList<Thread>() ;
			for (int i = 1; i <= threadNumber; i++)
			{
				final Executor exe = (Executor) executorClass.newInstance() ;
				exe.setDBHandler(soidb) ;
				th = new Thread((Runnable) exe) ;
				th.setName(executorClass.getSimpleName() + "-" + i) ;
				th.start() ;
				threads.add(th) ;
			}

			final Calendar stopTime = Calendar.getInstance() ;
			stopTime.add(Calendar.MINUTE, runPeriodMinutes) ;
			while (Calendar.getInstance().before(stopTime))
			{
				Thread.sleep(60000) ;
				System.out.println("1 more minute from " + runPeriodMinutes + " is over") ;
			}

			System.out.println("Run period is over") ;
			while (threads.size() > 0)
			{
				for (int i = 1; i < threads.size(); i++)
				{
					th = threads.get(i) ;
					System.out.println("Thread interrupting: " + th.getName()) ;
					th.interrupt() ;
					if (!th.isAlive())
					{
						System.out.println("Thread stopped: " + th.getName()) ;
						break ;
					}
				}
				Thread.sleep(60000) ;
				System.out.println("1 more minute from " + runPeriodMinutes + " is over") ;
			}

		}
		catch (final Exception e)
		{
			logger.severe("Error: " + e.getMessage()) ;
			e.printStackTrace() ;
		}
		finally
		{
			if (soidb != null)
				soidb.closeDBConnection() ;
		}
	}

	private static void printUssage()
	{
		System.out.println("Usage:\n" + SOILoaderClient.class.getSimpleName() + " <executorClassNname> <threadNumber> <runPeriod (minutes)>\n") ;
	}
}
